package com.itboye.jinpuyiyuan.activity.pay;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alipay.sdk.app.PayTask;
import com.ccb.ccbnetpay.CcbMorePay;
import com.ccb.ccbnetpay.message.CcbPayResultListener;

import com.ccb.ccbnetpay.util.IPUtil;
import com.itboye.jinpuyiyuan.R;
import com.itboye.jinpuyiyuan.app.MyApplication;
import com.itboye.jinpuyiyuan.base.BaseActivity;
import com.itboye.jinpuyiyuan.bean.PayInfo;
import com.itboye.jinpuyiyuan.presenter.BranchAddressPresenter;
import com.itboye.jinpuyiyuan.utils.TimeFormat;
import com.itboye.jinpuyiyuan.utils.alipay.OrderInfoUtil2_0;
import com.itboye.jinpuyiyuan.utils.alipay.PayResult;
import com.itboye.jinpuyiyuan.utils.sputil.Const;
import com.itboye.jinpuyiyuan.utils.sputil.SPUtils;
import com.itboye.jinpuyiyuan.utils.volley.ResultEntity;
import com.itboye.jinpuyiyuan.widget.loadingutil.MAlert;
import com.tencent.mm.opensdk.modelpay.PayReq;

import java.text.DecimalFormat;
import java.util.Map;
import java.util.Observable;
import java.util.Observer;

/**
 * Created by Administrator on 2018/5/3 0003.
 *
 */

public class PayActivity extends BaseActivity implements Observer {
    //title
    private ImageView back,rightImg;
    private TextView leftTv,tvTitle;
    private RelativeLayout rlLeft;

    private LinearLayout wxpayLayout,zfbpayLayout;
    private TextView payManeyTv,orderNumTv,orderDetailName;
    private CheckBox wx_check,zfbCheck;
    private TextView payTv;

    private String clientIp;

    private PayInfo bean,
            wx_bean,//微信bean
            zfb_bean;//支付宝的bean
    private long orderNum=2016110217972l;
    private BranchAddressPresenter presenter;
    String params1;
    String remark;
    String orderId;
    String uid;

    private static final int SDK_PAY_FLAG = 1;
    @Override
    protected void onCreate(Bundle arg0) {
        super.onCreate(arg0);
        setContentView(R.layout.activity_pay);

        wx_check.setChecked(true);
        tvTitle.setText("支付");
        uid= (String) SPUtils.get(this,null,Const.UID,"");
        Log.d("======uid",uid);
//        orderId="115287685017328U1143";
        orderId = getIntent().getStringExtra("order_id");
        remark = getIntent().getStringExtra("remark");
        presenter = new BranchAddressPresenter(this);
        showProgressDialog("正在获取支付信息...",false);
        presenter.getPayInfo(uid,orderId,"wechat_app",remark==null?"":remark);

//        商户编号：105000050470402
//        柜台代码：022502415
//        分行代码：211000000
        //支付宝
        IPUtil.getIPAddress();
        IPUtil.getIPAddress(new IPUtil.GetPhoneIPListener() {
            @Override
            public void success(String s) {
                clientIp=s;
            }

            @Override
            public void failed(String s) {

            }
        });
        params1="MERCHANTID=105000050470402&POSID=022502415&BRANCHID=211000000&ORDERID=2018082911&PAYMENT=0.01&CURCODE=01&TXCODE=520100&REMARK1=&REMARK2=&TYPE=1&PUB=f6528d5c335b7092fc9ec1b3020111&GATEWAY=&CLIENTIP=172.0.0.1&REGINFO=%u5C0F%u98DE%u4FA0&PROINFO=%u5145%u503C%u5361&REFERER=";
        bean=new PayInfo();

    }

//    @Override
//    protected void onRestart() {
//        super.onRestart();
//        wx_bean=null;
//        zfb_bean=null;
//    }

    @Override
    public void onClick(View view) {
        super.onClick(view);
        switch (view.getId()){
            case R.id.back://返回
                this.finish();
                break;

            case R.id.wxpayLayout://微信
            case R.id.wx_check:
                wx_check.setChecked(true);
                zfbCheck.setChecked(false);
                break;

            case R.id.zfbpayLayout://支付宝
            case R.id.zfbCheck:
                wx_check.setChecked(false);
                zfbCheck.setChecked(true);
                break;
            case R.id.payTv:
                if (zfbCheck.isChecked()){
                   if (zfb_bean==null){
                        payTv.setEnabled(false);
                        showProgressDialog("正在获取支付信息...",false);
                        presenter.getPayInfo(uid,orderId,"alipay_app",remark==null?"":remark);
                        return;
                   }else {
                        zfb(zfb_bean);
                        return;
                           }
                }
                if(wx_check.isChecked()){
                   if (wx_bean==null){
                        payTv.setEnabled(false);
                        //待开发
//                    MAlert.alert("微信支付待开发,请选择支付宝支付");
//                    payTv.setEnabled(true);
                        showProgressDialog("正在获取支付信息...",false);
                        presenter.getPayInfo(uid,orderId,"wechat_app",remark==null?"":remark);
                        return;
                   }else {
                        sendPayRequest(wx_bean);
                        return;
                           }
                }
                break;
        }
    }

    //支付监控回调
    CcbPayResultListener listener = new CcbPayResultListener() {
        @Override
        public void onSuccess(Map<String, String> result) {
            Log.d("registerdetail", "成功 --"+result);
            MAlert.alert("成功");
            for (Map.Entry entry : result.entrySet()) {
                Log.d("registerdetail", "key --"+entry.getKey()+"  value --"+entry.getValue());
            }
        }

        @Override
        public void onFailed(String msg) {
            MAlert.alert("失败");
            Log.d("registerdetail", "失败 --"+msg);
        }
    };

    /**
     * 字段名 	变量名 	类型 	必填 	示例值 	描述
     应用ID 	appid 	String(32) 	是 	wx8888888888888888 	微信开放平台审核通过的应用APPID
     商户号 	partnerid 	String(32) 	是 	1900000109 	微信支付分配的商户号
     预支付交易会话ID 	prepayid 	String(32) 	是 	WX1217752501201407033233368018 	微信返回的支付交易会话ID
     扩展字段 	package 	String(128) 	是 	Sign=WXPay 	暂填写固定值Sign=WXPay
     随机字符串 	noncestr 	String(32) 	是 	5K8264ILTKCH16CQ2502SI8ZNMTM67VS 	随机字符串，不长于32位。推荐随机数生成算法
     时间戳 	timestamp 	String(10) 	是 	1412000000 	时间戳，请见接口规则-参数规定
     签名 	sign 	String(32) 	是 	C380BEC2BFD727A4B6845133519F3AD6 	签名，详见签名生成算法注意：签名方式一定要与统一下单接口使用的一致
     */

    /**调用微信支付*/
    public void sendPayRequest(PayInfo payInfo) {
        PayReq req = new PayReq();
        req.appId = payInfo.getWx_pay_info().getOrder_arr().getAppid();
        req.partnerId = payInfo.getWx_pay_info().getOrder_arr().getPartnerid(); //商户号
        req.prepayId = payInfo.getWx_pay_info().getOrder_arr().getPrepayid();
        req.nonceStr = payInfo.getWx_pay_info().getOrder_arr().getNoncestr();
        req.timeStamp = payInfo.getWx_pay_info().getOrder_arr().getTimestamp();
        req.packageValue = payInfo.getWx_pay_info().getOrder_arr().getPakage();
        req.sign =payInfo.getWx_pay_info().getOrder_arr().getSign();
        // 在支付之前，如果应用没有注册到微信，应该先调用IWXMsg.registerApp将应用注册到微信
        //3.调用微信支付sdk支付方法
        MyApplication.instatnce.api.sendReq(req);
    }
    /**
     * 支付宝
     */
    private void zfb(final PayInfo bean) {
        /**
         * 这里只是为了方便直接向商户展示支付宝的整个支付流程；所以Demo中加签过程直接放在客户端完成；
         * 真实App里，privateKey等数据严禁放在客户端，加签过程务必要放在服务端完成；
         * 防止商户私密数据泄露，造成不必要的资金损失，及面临各种安全风险；
         * orderInfo的获取必须来自服务端；
         */

        //手动拼接alipay 支付信息
        Log.d("======bean",bean.toString());
        Map<String, String> params = OrderInfoUtil2_0.buildOrderParamMap(Const.APPID, true,bean);
        String orderParam = OrderInfoUtil2_0.buildOrderParam(params);

        String sign = OrderInfoUtil2_0.getSign(params, Const.RSA_PRIVATE, true);
        final String orderInfo = orderParam + "&" + sign;

        Log.d("pay=====",orderInfo.toString());
        Runnable payRunnable = new Runnable() {
            @Override
            public void run() {
                PayTask alipay = new PayTask(PayActivity.this);

                Map<String, String> result = alipay.payV2(orderInfo, true);
//                Map<String, String> result = alipay.payV2(bean.getAli_pay_info(), true);
                Message msg = new Message();
                msg.what = SDK_PAY_FLAG;
                msg.obj = result;
                mHandler.sendMessage(msg);
            }
        };

        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }

    private Handler mHandler = new Handler() {
        @SuppressWarnings("unused")
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {

                    PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                    /**
                     对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                     */
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();
                    // 判断resultStatus 为9000则代表支付成功
                    if (TextUtils.equals(resultStatus, "9000")) {
                        // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
                        Toast.makeText(PayActivity.this, "支付成功", Toast.LENGTH_SHORT).show();
                        finish();
                    } else {
                        // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                        Toast.makeText(PayActivity.this, "支付失败", Toast.LENGTH_SHORT).show();
                    }
                    break;
                }

                default:
                    break;
            }
        }
    };

    @Override
    public void update(Observable o, Object arg) {

        ResultEntity entity = handlerError(arg);

        if (entity!=null){

            if (entity.getEventType() ==BranchAddressPresenter.By_Order_prePay_success ){
                try{
                    closeProgressDialog();
                }catch (Exception e){

                }

                bean= (PayInfo) entity.getData();
                orderNumTv.setText(bean.getOrder_code());
                orderDetailName.setText(bean.getSubject());
                DecimalFormat df ;
                int money = Integer.parseInt(bean.getAmount());
                double format = (double)money/100;

                if (format<1){
                    df = new DecimalFormat("#0.00");
                }else {
                    df = new DecimalFormat("#.00");
                }
                if (zfbCheck.isChecked()){
                    payManeyTv.setText("￥"+df.format(format));
                    zfb_bean=bean;
                        zfb(bean);

                    }else {
                    payManeyTv.setText("￥"+df.format(format));
                    if (bean.getWx_pay_info().getSuccess().trim().equals("1")){ //获取微信支付信息成功
                        if (!payTv.isEnabled()){
                            wx_bean=bean;
                            sendPayRequest(bean);
                        }
                    }else {
                        MAlert.alert(bean.getWx_pay_info().getData());
                    }

                    }
                payTv.setEnabled(true);
            }else if (entity.getEventType() == BranchAddressPresenter.By_Order_prePay_faile){

                try{
                    closeProgressDialog();
                }catch (Exception e){

                }
                MAlert.alert(entity.getMsg());
                payTv.setEnabled(true);
            }
        }
    }

}
